package com.toivan.mt.views;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.shizhefei.view.indicator.FragmentListPageAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.shizhefei.view.viewpager.SViewPager;
import com.toivan.mt.R;
import com.toivan.mt.fragment.MtAtmosphereFragment;
import com.toivan.mt.fragment.MtBeautyFragment;
import com.toivan.mt.fragment.MtCuteStickerFragment;
import com.toivan.mt.fragment.MtDeleteGreenScreenDialog;
import com.toivan.mt.fragment.MtEffectFilterFragment;
import com.toivan.mt.fragment.MtExpressionFragment;
import com.toivan.mt.fragment.MtFaceShapeFragment;
import com.toivan.mt.fragment.MtFestivalStickerFragment;
import com.toivan.mt.fragment.MtFilterFragment;
import com.toivan.mt.fragment.MtFunnyFilterFragment;
import com.toivan.mt.fragment.MtGreenScreenFragment;
import com.toivan.mt.fragment.MtHotStickerFragment;
import com.toivan.mt.fragment.MtMagicFilterFragment;
import com.toivan.mt.fragment.MtMaskFragment;
import com.toivan.mt.fragment.MtPortraitFragment;
import com.toivan.mt.fragment.MtQuickBeautyFragment;
import com.toivan.mt.fragment.MtToneFilterFragment;
import com.toivan.mt.fragment.MtWatermarkFragment;
import com.toivan.mt.model.MtBeautyMode;
import com.toivan.mt.model.MtDynamicSticker;
import com.toivan.mt.model.MtGreenScreen;
import com.toivan.mt.model.RxBusAction;
import com.toivan.mt.utils.MtResetDialogFragment;
import com.toivan.mt.utils.MtSharedPreferences;
import com.toivan.sdk.MtSDK;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MtBeautyView extends LinearLayout {
    private MtSDK mtSDK;
    private ScrollIndicatorView indicatorView;
    public MtBarView mtBarView;

    private LinearLayout enableLL;
    private TextView enableTV;
    private ImageView enableIV;
    private View dividerV;
    private SViewPager viewPager;
    private TextView btnReset;
    private View btnCancel;
    private TextView btnDelete;//删除按钮
    private View btnBack;

    private final List<Integer> tabs = new ArrayList<>();

    private boolean isBeautyEnable = false;
    private boolean isFaceShapeEnable = false;

    private int beautyMode = MtBeautyMode.MODE_BEAUTY;
    private IndicatorViewPager.IndicatorFragmentPagerAdapter fragmentPagerAdapter;

    private MtHotStickerFragment hotStickerFragment;
    private MtFestivalStickerFragment festivalStickerFragment;
    private MtCuteStickerFragment cuteStickerFragment;
    private MtExpressionFragment expressionFragment;
    private MtMaskFragment maskFragment;
    private MtAtmosphereFragment atmosphereFragment;
    private MtWatermarkFragment watermarkFragment;
    private MtPortraitFragment portraitFragment;
    private MtGreenScreenFragment greenScreenFragment;


    public MtBeautyView(Context context) {
        super(context);
    }


    public MtBeautyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }


    public MtBeautyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MtBeautyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }


    public MtBeautyView init(MtSDK mtSDK) {
        this.mtSDK = mtSDK;

        RxBus.get().register(this);

        initView();

        initData();

        return this;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        RxBus.get().unregister(this);
    }


    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_mt_beauty, this);

        mtBarView = findViewById(R.id.mtBarView);
        mtBarView.init(mtSDK);

        indicatorView = findViewById(R.id.indicatorView);

        enableLL = findViewById(R.id.enableLL);
        enableTV = findViewById(R.id.enableTV);
        enableIV = findViewById(R.id.enableIV);
        dividerV = findViewById(R.id.dividerV);
        viewPager = findViewById(R.id.viewPager);
        btnReset = findViewById(R.id.btn_reset);
        btnCancel = findViewById(R.id.btn_cancel);
        btnDelete = findViewById(R.id.btn_delete);
        btnBack = findViewById(R.id.btn_back);
    }

    private void initData() {

        //屏蔽点击事件
        setOnClickListener(null);

        isBeautyEnable = MtSharedPreferences.getInstance().isFaceBeautyEnable();
        mtSDK.setFaceBeautyEnable(isBeautyEnable);
        isFaceShapeEnable = MtSharedPreferences.getInstance().isFaceShapeEnable();
        mtSDK.setFaceShapeEnable(isFaceShapeEnable);
        enableIV.setSelected(isBeautyEnable);
        enableTV.setSelected(isBeautyEnable);

        enableTV.setText(isBeautyEnable ? R.string.beauty_on : R.string.beauty_off);

        greenScreenFragment = new MtGreenScreenFragment();

        changeResetStatus(MtSharedPreferences.getInstance().isBtnResetEnable());
        //点击删除按钮
        btnDelete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (beautyMode == MtBeautyMode.MODE_GREEN_SCREEBN) {
                    if (MtSharedPreferences.getInstance().getGreenScreenPosition() != -1 && greenScreenFragment != null) {
                        //选中item时候
                        final MtGreenScreen greenScreen = greenScreenFragment.list.get(MtSharedPreferences.getInstance().getGreenScreenPosition());
                        if (!greenScreen.isFromDisk()) {
                            return;
                        }

                        showDeleteDialog(new MtDeleteGreenScreenDialog.MtDeleteGreenScreenDialogButtonClick() {
                            @Override
                            public void clickYeep() {
                                //点击确定时
                                greenScreen.setName(MtSharedPreferences.getInstance().getGreenScreen());
                                greenScreen.greenScreenDelete(getContext());
                                greenScreenFragment.updateDelete(MtSharedPreferences.getInstance().getGreenScreenPosition());
                                mtSDK.setGreenScreenName("");
                                MtSharedPreferences.getInstance().setGreenScreenName("", -1);
                                new File(greenScreen.getDir()).delete();
                            }

                            @Override
                            public void clickNo() {
                                //点击取消时
                            }
                        });

                    }
                }
            }
        });

        btnReset.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showResetDialog();
            }
        });
        btnCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (beautyMode == MtBeautyMode.MODE_STICKER) {
                    mtSDK.setDynamicStickerName("");
                    MtSharedPreferences.getInstance().setDynamicStickerName("");

                    cancelHotSelected();
                    cancelFestivalSelected();
                    cancelCuteSelected();
                } else if (beautyMode == MtBeautyMode.MODE_EXPRESSION) {
                    expressionFragment.cancelExpression();
                } else if (beautyMode == MtBeautyMode.MODE_MASK) {
                    maskFragment.cancelMask();
                } else if (beautyMode == MtBeautyMode.MODE_ATMOSPHERE) {
                    atmosphereFragment.cancelAtmosphere();
                } else if (beautyMode == MtBeautyMode.MODE_WATERMARK) {
                    watermarkFragment.cancelWatermark();
                } else if (beautyMode == MtBeautyMode.MODE_PORTRAIT) {
                    portraitFragment.cancelPortrait();
                } else if (beautyMode == MtBeautyMode.MODE_GREEN_SCREEBN) {
                    greenScreenFragment.cancelGreenScreen();
                }

                btnCancel.setEnabled(false);
            }
        });

        enableLL.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (beautyMode == MtBeautyMode.MODE_BEAUTY) {
                    isBeautyEnable = !isBeautyEnable;
                    mtSDK.setFaceBeautyEnable(isBeautyEnable);
                    MtSharedPreferences.getInstance().setFaceBeautyEnable(isBeautyEnable);
                    enableIV.setSelected(isBeautyEnable);
                    enableTV.setSelected(isBeautyEnable);
                    enableTV.setText(isBeautyEnable ? R.string.beauty_on : R.string.beauty_off);
                    mtBarView.selectBeauty();
                } else if (beautyMode == MtBeautyMode.MODE_FACE_SHAPE) {
                    isFaceShapeEnable = !isFaceShapeEnable;
                    mtSDK.setFaceShapeEnable(isFaceShapeEnable);
                    MtSharedPreferences.getInstance().setFaceShapeEnable(isFaceShapeEnable);
                    enableIV.setSelected(isFaceShapeEnable);
                    enableTV.setSelected(isFaceShapeEnable);
                    enableTV.setText(isFaceShapeEnable ? R.string.face_trim_on : R.string.face_trim_off);
                    mtBarView.selectFaceTrim();
                }
            }
        });

        tabs.clear();
        tabs.add(R.string.face_beauty);
        enableIV.setSelected(isBeautyEnable);
        enableTV.setSelected(isBeautyEnable);
        enableTV.setText(isBeautyEnable ? R.string.beauty_on : R.string.beauty_off);
        RxBus.get().post(RxBusAction.ACTION_WHITENESS);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                indicatorView.getIndicatorAdapter().notifyDataSetChanged();
                if (beautyMode == MtBeautyMode.MODE_FILTER) {
                    switch (position) {
                        case 0:
                            break;
                        case 1:
                            mtBarView.selectEffectFilter();
                            break;
                        case 2:
                        case 3:
                            mtBarView.hideSeekBar();
                            break;
                        case 4:
                            mtBarView.selectToneFilter();
                            break;
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        indicatorView.setSplitAuto(false);
        IndicatorViewPager indicatorViewPager = new IndicatorViewPager(indicatorView, viewPager);
        viewPager.setCanScroll(false);
        indicatorViewPager.setPageOffscreenLimit(6);
        fragmentPagerAdapter = new IndicatorViewPager.IndicatorFragmentPagerAdapter(((FragmentActivity) getContext()).getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return tabs.size();
            }

            @Override
            public View getViewForTab(int position, View convertView, ViewGroup container) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_indicator_tab, container, false);

                if (position == 0 && !MtBeautyPanel.isCuteClassVisible) {
                    ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) convertView.getLayoutParams();
                    p.setMargins((int) (convertView.getContext().getResources().getDisplayMetrics().density * 16 + 0.5f), 0, 0, 0);
                    convertView.requestLayout();
                } else {
                    ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) convertView.getLayoutParams();
                    p.setMargins(0, 0, 0, 0);
                    convertView.requestLayout();
                }
                ((TextView) convertView).setText(convertView.getContext().getResources().getString(tabs.get(position)));
                return convertView;
            }

            @Override
            public int getItemPosition(Object object) {
                return FragmentListPageAdapter.POSITION_NONE;
            }

            @Override
            public Fragment getFragmentForPage(int position) {
                if (beautyMode == MtBeautyMode.MODE_BEAUTY) {
                    return new MtBeautyFragment();
                } else if (beautyMode == MtBeautyMode.MODE_FACE_SHAPE) {
                    return new MtFaceShapeFragment();
                } else if (beautyMode == MtBeautyMode.MODE_FILTER) {
                    switch (position) {
                        case 0:
                            return new MtFilterFragment();
                        case 1:
                            return new MtEffectFilterFragment();
                        case 2:
                            return new MtFunnyFilterFragment();
                        case 3:
                            return new MtMagicFilterFragment();
                        case 4:
                            return new MtToneFilterFragment();
                    }
                } else if (beautyMode == MtBeautyMode.MODE_QUICK_BEAUTY) {
                    return new MtQuickBeautyFragment();
                } else if (beautyMode == MtBeautyMode.MODE_STICKER) {
                    boolean enable = MtSharedPreferences.getInstance().getHotStickerPosition() != -1 || MtSharedPreferences.getInstance().getFestivalStickerPosition() != -1 || MtSharedPreferences.getInstance().getCuteStickerPosition() != -1;
                    btnCancel.setEnabled(enable);
                    switch (position) {
                        case 0:
                            hotStickerFragment = new MtHotStickerFragment();
                            return hotStickerFragment;
                        case 1:
                            festivalStickerFragment = new MtFestivalStickerFragment();
                            return festivalStickerFragment;
                        case 2:
                            cuteStickerFragment = new MtCuteStickerFragment();
                            return cuteStickerFragment;
                    }
                } else if (beautyMode == MtBeautyMode.MODE_EXPRESSION) {
                    btnCancel.setEnabled(MtSharedPreferences.getInstance().getExpressionPosition() != -1);
                    expressionFragment = new MtExpressionFragment();
                    return expressionFragment;
                } else if (beautyMode == MtBeautyMode.MODE_MASK) {
                    btnCancel.setEnabled(MtSharedPreferences.getInstance().getMaskPosition() != -1);
                    maskFragment = new MtMaskFragment();
                    return maskFragment;
                } else if (beautyMode == MtBeautyMode.MODE_ATMOSPHERE) {
                    btnCancel.setEnabled(MtSharedPreferences.getInstance().getAtmospherePosition() != -1);
                    atmosphereFragment = new MtAtmosphereFragment();
                    return atmosphereFragment;
                } else if (beautyMode == MtBeautyMode.MODE_WATERMARK) {
                    btnCancel.setEnabled(MtSharedPreferences.getInstance().getWatermarkPosition() != -1);
                    watermarkFragment = new MtWatermarkFragment();
                    return watermarkFragment;
                } else if (beautyMode == MtBeautyMode.MODE_PORTRAIT) {
                    btnCancel.setEnabled(MtSharedPreferences.getInstance().getPortraitPosition() != -1);
                    portraitFragment = new MtPortraitFragment();
                    return portraitFragment;
                } else if (beautyMode == MtBeautyMode.MODE_GREEN_SCREEBN) {
                    btnCancel.setEnabled(MtSharedPreferences.getInstance().getGreenScreenPosition() != -1);
                    greenScreenFragment = new MtGreenScreenFragment();
                    return greenScreenFragment;
                }
                return null;
            }
        };

        indicatorViewPager.setAdapter(fragmentPagerAdapter);
    }


    public void refreshData(int mode) {
        MtBeautyPanel.isCuteClassVisible = false;
        if (btnCancel != null) {
            btnCancel.setVisibility(GONE);
        }

        //默认隐藏删除按钮
        if (btnDelete != null) {
            btnDelete.setVisibility(GONE);
        }

        beautyMode = mode;
        viewPager.setCurrentItem(0);
        tabs.clear();

        if (beautyMode == MtBeautyMode.MODE_BEAUTY) {
            tabs.add(R.string.face_beauty);

            enableLL.setVisibility(VISIBLE);
            dividerV.setVisibility(VISIBLE);

            mtBarView.selectBeauty();

            isBeautyEnable = MtSharedPreferences.getInstance().isFaceBeautyEnable();
            enableIV.setSelected(isBeautyEnable);
            enableTV.setSelected(isBeautyEnable);
            enableTV.setText(isBeautyEnable ? R.string.beauty_on : R.string.beauty_off);

            RxBus.get().post(RxBusAction.ACTION_WHITENESS);
        } else if (beautyMode == MtBeautyMode.MODE_FACE_SHAPE) {
            tabs.add(R.string.face_shape);

            enableLL.setVisibility(VISIBLE);
            dividerV.setVisibility(VISIBLE);

            mtBarView.selectFaceTrim();

            isFaceShapeEnable = MtSharedPreferences.getInstance().isFaceShapeEnable();
            enableIV.setSelected(isFaceShapeEnable);
            enableTV.setSelected(isFaceShapeEnable);
            enableTV.setText(isFaceShapeEnable ? R.string.face_trim_on : R.string.face_trim_off);

            RxBus.get().post(RxBusAction.ACTION_EYE_ENLARGING);
        } else if (beautyMode == MtBeautyMode.MODE_FILTER) {
            tabs.add(R.string.beauty_filter);
            tabs.add(R.string.effect_filter);
            tabs.add(R.string.funny_filter);
            tabs.add(R.string.magic_filter);
            tabs.add(R.string.tone_filter);

            enableLL.setVisibility(GONE);
            dividerV.setVisibility(GONE);

            // mtBarView.selectFilter();
        } else if (beautyMode == MtBeautyMode.MODE_QUICK_BEAUTY) {
            tabs.add(R.string.quick_beauty);

            enableLL.setVisibility(GONE);
            dividerV.setVisibility(GONE);

            // mtBarView.selectQuickBeauty();
        }

        indicatorView.setOnTransitionListener(new OnTransitionTextListener()
            .setColor(getResources().getColor(R.color.mt_selected), getResources().getColor(R.color.mt_unselected)));
        fragmentPagerAdapter.notifyDataSetChanged();
    }

    public void refreshCuteData(int mode) {
        MtBeautyPanel.isCuteClassVisible = true;
        if (btnCancel != null) {
            btnCancel.setVisibility(VISIBLE);
        }

        if (btnDelete != null) {
            btnDelete.setVisibility(GONE);
        }

        if (btnBack != null && !btnBack.isShown()) {
            btnBack.setVisibility(VISIBLE);
        }

        beautyMode = mode;

        viewPager.setCurrentItem(0);

        tabs.clear();

        switch (mode) {
            case MtBeautyMode.MODE_STICKER:
                tabs.add(R.string.hot);
                tabs.add(R.string.festival);
                tabs.add(R.string.cute_series);
                break;
            case MtBeautyMode.MODE_EXPRESSION:
                tabs.add(R.string.expression_recreation);
                break;
            case MtBeautyMode.MODE_MASK:
                tabs.add(R.string.mask);
                break;
            case MtBeautyMode.MODE_ATMOSPHERE:
                tabs.add(R.string.atmosphere_sticker);
                break;
            case MtBeautyMode.MODE_WATERMARK:
                tabs.add(R.string.watermark);
                break;
            //人像抠图
            case MtBeautyMode.MODE_PORTRAIT:
                tabs.add(R.string.portrait);
                break;
            //绿幕
            case MtBeautyMode.MODE_GREEN_SCREEBN:
                tabs.add(R.string.green_screen);
                btnDelete.setVisibility(VISIBLE);
                btnBack.setVisibility(GONE);
                break;
        }
        enableLL.setVisibility(GONE);

        dividerV.setVisibility(GONE);

        mtBarView.hideSeekBar();

        indicatorView.setOnTransitionListener(new OnTransitionTextListener()
            .setColor(getResources().getColor(R.color.mt_selected), getResources().getColor(R.color.mt_unselected_cute)));
        fragmentPagerAdapter.notifyDataSetChanged();
    }

    //显示重置弹窗
    private void showResetDialog() {
        FragmentActivity activity = (FragmentActivity) getContext();
        MtResetDialogFragment dialogFragment = new MtResetDialogFragment();
        dialogFragment.show(activity.getSupportFragmentManager(), "MtResetDialogFragment");
    }

    /**
     * 显示删除弹窗
     *
     * @param buttonClick 点击事件的回调
     */
    private void showDeleteDialog(@Nullable MtDeleteGreenScreenDialog.MtDeleteGreenScreenDialogButtonClick buttonClick) {
        FragmentActivity activity = (FragmentActivity) getContext();
        MtDeleteGreenScreenDialog dialogFragment = new MtDeleteGreenScreenDialog();
        if (buttonClick != null) dialogFragment.setButtonClick(buttonClick);
        dialogFragment.show(activity.getSupportFragmentManager(), "MtDeleteDialogFragment");
    }

    private void cancelHotSelected() {
        MtSharedPreferences.getInstance().setHotStickerPosition(-1);
        if (hotStickerFragment != null) {
            hotStickerFragment.cancelSticker();
        }
    }

    private void cancelFestivalSelected() {
        MtSharedPreferences.getInstance().setFestivalStickerPosition(-1);
        if (festivalStickerFragment != null) {
            festivalStickerFragment.cancelSticker();
        }
    }

    private void cancelCuteSelected() {
        MtSharedPreferences.getInstance().setCuteStickerPosition(-1);
        if (cuteStickerFragment != null) {
            cuteStickerFragment.cancelSticker();
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
               tags = {
                   @Tag(RxBusAction.ACTION_RESET_IS_ENABLED)
               })
    public void changeResetStatus(Boolean isEnabled) {
        if (isEnabled) {
            if (!btnReset.isEnabled()) {
                btnReset.setEnabled(true);
                MtSharedPreferences.getInstance().setBtnResetEnable(true);
            }
        } else {
            if (btnReset.isEnabled()) {
                btnReset.setEnabled(false);
                MtSharedPreferences.getInstance().setBtnResetEnable(false);

                if (beautyMode == MtBeautyMode.MODE_BEAUTY || beautyMode == MtBeautyMode.MODE_FACE_SHAPE) {
                    mtBarView.busCurrentAction(mtBarView.currentAction);
                }
            }
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
               tags = {
                   @Tag(RxBusAction.ACTION_ENABLE_CANCEL)
               })
    public void enableBtnCancel(String category) {
        if (btnCancel != null) {
            btnCancel.setEnabled(true);
        }
        if (!TextUtils.isEmpty(category)) {
            if (!category.equals(MtDynamicSticker.CATEGORY_DEFAULT)) {
                cancelHotSelected();
            }
            if (!category.equals(MtDynamicSticker.CATEGORY_FESTIVAL)) {
                cancelFestivalSelected();
            }
            if (!category.equals(MtDynamicSticker.CATEGORY_CUTE)) {
                cancelCuteSelected();
            }
        }
    }

    /**
     * 监听绿幕点击事件来设定字体颜色
     *
     * @param value 暂时无意义
     */
    @Subscribe(thread = EventThread.MAIN_THREAD,
               tags = {
                   @Tag(RxBusAction.ACTION_SELECT_GREEN_SCREEN)
               }
    )
    public void greenScreenSelected(String value) {
        if (MtSharedPreferences.getInstance().getGreenScreenPosition() != -1
            && greenScreenFragment != null && greenScreenFragment.list.size() != 0) {

            final MtGreenScreen greenScreen = greenScreenFragment.list.get(MtSharedPreferences.getInstance().getGreenScreenPosition());

            if (greenScreen.isFromDisk()) {
                btnDelete.setEnabled(true);
                btnDelete.setTextColor(getResources().getColor(android.R.color.white));
            } else {
                btnDelete.setEnabled(false);
                btnDelete.setTextColor(getResources().getColor(R.color.mt_text_unselected));
            }
        } else {
            btnDelete.setEnabled(false);
            btnDelete.setTextColor(getResources().getColor(R.color.mt_text_unselected));
        }
    }

}




